package com.tzbank.poc.controller;

import com.tzbank.poc.common.CommonConstant;
import com.tzbank.poc.model.AccountBalance;
import com.tzbank.poc.model.AccountBalanceKey;
import com.tzbank.poc.model.Trade;
import com.tzbank.poc.service.AccountBalanceService;
import com.tzbank.poc.service.TradeService;
import com.tzbank.poc.util.IdUtil;
import com.tzbank.poc.util.ReturnMapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/1/23 0023.
 */
@Controller
@RequestMapping(value = "/trade")
public class TradeController {

    @Autowired
    private TradeService tradeService;

    @Autowired
    private AccountBalanceService accounBalanceService;

    private Logger logger = LoggerFactory.getLogger(TradeController.class);

    @ResponseBody
    @RequestMapping(value="/addTradeInfo", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> addTradeInfo(@RequestBody Map map) throws Exception{
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        String accountNo = bodyMap.get("accountNo").toString();
        String tradeType = bodyMap.containsKey("tradeType")?bodyMap.get("tradeType").toString() :"";
        BigDecimal tradeAmount = bodyMap.containsKey("tradeAmount")?new BigDecimal(bodyMap.get("tradeAmount").toString()):new BigDecimal(0);
        String tradeAccount = bodyMap.containsKey("tradeAccount")? bodyMap.get("tradeAccount").toString():"";
        String tradeTime = bodyMap.containsKey("tradeTime")? bodyMap.get("tradeTime").toString() : formatter.format(new Date());
        String paymentType = bodyMap.containsKey("paymentType")? bodyMap.get("paymentType").toString():"";
        String tradeDescription = bodyMap.containsKey("tradeDescription")?bodyMap.get("tradeDescription").toString():"";
        String tradeUom = bodyMap.containsKey("tradeUom")? bodyMap.get("tradeUom").toString():"";
        String tradeInfo = bodyMap.containsKey("tradeInfo")? bodyMap.get("tradeInfo").toString():"";
        String tradeStatus = bodyMap.containsKey("tradeStatus")? bodyMap.get("tradeStatus").toString() :"";

        Trade trade = new Trade();

        trade.setAccountNo(accountNo);
        trade.setPaymentAmount(tradeAmount);
        trade.setPaymentType(paymentType);
        trade.setTradeAccount(tradeAccount);
        trade.setTradeDescription(tradeDescription);
        trade.setTradeInfo(tradeInfo);
        trade.setTradeStatus(tradeStatus);
        trade.setTradeTime(formatter.parse(tradeTime));
        trade.setTradeUom(tradeUom);
        trade.setTradeType(tradeType);
        trade.setUserNo(userNo);
        String tradeSeq = IdUtil.getTradeSeq(userNo);
        trade.setTradeSeq(tradeSeq);
        tradeService.addTradeInfo(trade);
        Map body = new HashMap();
        body.put("tradeSeq",tradeSeq);
        ReturnMapUtil.setBodyMap(body);
        //更新账户余额
        if(CommonConstant.PAY_ACCOUNT.equals(paymentType) || CommonConstant.REGIST.equals(tradeType)){
            AccountBalanceKey accountBalanceKey = new AccountBalanceKey();
            accountBalanceKey.setAccountNo(accountNo);
            accountBalanceKey.setUserNo(userNo);
            AccountBalance ac = accounBalanceService.queryAccountBalance(accountBalanceKey);
            BigDecimal balanceAmount = ac.getAccountBalance();
            balanceAmount = balanceAmount.add(tradeAmount);
            AccountBalance accountBalance = new AccountBalance();
            accountBalance.setAccountBalance(balanceAmount);
            accountBalance.setAccountNo(accountNo);
            accountBalance.setUserNo(userNo);
            accounBalanceService.updateBalance(accountBalance);
        }

        return  ReturnMapUtil.getSuccessMap();
    }

    @ResponseBody
    @RequestMapping(value="/queryTradeInfoDetail", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> queryTradeInfoDetail(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);

        String tradeSeq = bodyMap.get("tradeSeq").toString();

        Trade tradeinfo = tradeService.queryTradeInfoDetail(tradeSeq);
        Map tradeMap = new HashMap();
        Class ta = tradeinfo.getClass();
        Field[] fields = ta.getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            boolean flag = field.isAccessible();
            field.setAccessible(true);
            try {
                tradeMap.put(field.getName(), field.get(tradeinfo));
            } catch (IllegalAccessException e) {
                ReturnMapUtil.returnFail(e.getMessage());
            }
            field.setAccessible(flag);
        });
        ReturnMapUtil.setBodyMap(tradeMap);

        return ReturnMapUtil.getSuccessMap();
    }

    @ResponseBody
    @RequestMapping(value="/queryInAndOut", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> queryInAndOut(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);

        BigDecimal inAmount = tradeService.queryInAmount(bodyMap) ;
        BigDecimal outAmount = tradeService.queryOutAmount(bodyMap);
        Map<String,Object> body = new HashMap<>();
        body.put("tradeOutAmount",outAmount!=null?outAmount:new BigDecimal(0));
        body.put("tradeInAmount",inAmount != null?inAmount: new BigDecimal(0));
        ReturnMapUtil.setBodyMap(body);

        return ReturnMapUtil.getSuccessMap();
    }

    @ResponseBody
    @RequestMapping(value="/queryAccountBalance", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object> queryAccountBalance(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        String userNo = bodyMap.get("userNo").toString();
        String accountNo = bodyMap.get("accountNo").toString();

        AccountBalanceKey accountBalanceKey = new AccountBalanceKey();
        accountBalanceKey.setAccountNo(accountNo);
        accountBalanceKey.setUserNo(userNo);

        AccountBalance accounBalance = accounBalanceService.queryAccountBalance(accountBalanceKey);
        Map returnBody = new HashMap<>();
        returnBody.put("accountNo",accountNo);
        returnBody.put("accountBalance",accounBalance.getAccountBalance());
        returnBody.put("uomId",accounBalance.getUomId());
        ReturnMapUtil.setBodyMap(returnBody);

        return ReturnMapUtil.getSuccessMap();
    }

    @ResponseBody
    @RequestMapping(value = "/queryTradeList", produces = {"application/json;charset=UTF-8"})
    public Map<String,Object>queryTradeList(@RequestBody Map map) throws Exception{
        Map bodyMap = ReturnMapUtil.getBody(map);
        int intPage = bodyMap.containsKey("intPage")?Integer.parseInt(bodyMap.get("intPage").toString()):1;
        int pageNum = bodyMap.containsKey("pageNum")?Integer.parseInt(bodyMap.get("pageNum").toString()):10;

        List<Trade> tradeList = tradeService.queryTradeList(bodyMap, pageNum, intPage);
        Map<String,Object> listMap = new HashMap<>();
        listMap.put("tradeList",tradeList);
        ReturnMapUtil.setBodyMap(listMap);
        return ReturnMapUtil.getSuccessMap();
    }

}
